package cn.com.hhrcw.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.hhrcw.annotation.Column;
import cn.com.hhrcw.area.entity.SysArea;
import cn.com.hhrcw.area.service.ISysAreaService;
import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.mapstruct.EnInfoAdminConvert;
import cn.com.hhrcw.params.EnInfoAdminParams;
import cn.com.hhrcw.position.entity.SysIndustry;
import cn.com.hhrcw.position.service.ISysIndustryService;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.vo.*;
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.annotation.ExcelProperty;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.Dict;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;

import cn.com.hhrcw.mapstruct.CvResumeStatisticsConvert;
import cn.com.hhrcw.params.CvResumeStatisticsParams;
import cn.com.hhrcw.params.EntryParam;
import cn.com.hhrcw.params.StatisticsInfoParams;
import cn.com.hhrcw.position.entity.RecruitmentPosition;
import cn.com.hhrcw.position.service.IRecruitmentPositionService;
import cn.com.hhrcw.utils.DateUtil;
import cn.com.hhrcw.utils.ExcelUtil;
import cn.com.hhrcw.utils.ProvinceCityCountyUtils;
import cn.com.hhrcw.utils.edu.EduLabelUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 导出excel
 *
 * @program: recruit-boot-parent
 * @description: 导出excel
 * @author: JD
 * @create: 2020-11-13 10:31
 **/
@RestController
@RequestMapping("/admin/excel")
@Slf4j
public class ExcelController {

    @Value(value = "${jeecg.path.upload}")
    private String uploadPath;

    @Autowired
    private EduLabelUtil eduLabelUtil;

    @Autowired
    private ICvResumeStatisticsService cvResumeStatisticsService;

    @Autowired
    private CvResumeStatisticsConvert cvResumeStatisticsConvert;

    @Autowired
    private IOpDeliveryHistoryService deliveryHistoryService;

    @Autowired
    private ICvSkillsService cvSkillsService;

    @Autowired
    private IOpJobService jobService;

    @Autowired
    private IOpInterviewHistoryService interviewHistoryService;

    @Autowired
    AdminService enterpriseService;

    @Autowired
    ISysUserDepartService userDepartService;

    @Autowired
    private ICvResumeService resumeService;

    @Autowired
    private IEnInfoService enInfoService;

    @Autowired
    private EnInfoAdminConvert enInfoAdminConvert;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private ICvUserEduInfoService eduInfoService;

    @Autowired
    private ICvUserWorkInfoService workInfoService;

    @Autowired
    private ICvWorkIntentionService workIntentionService;

    @Autowired
    private ICvCertificateService certificateService;

    @Autowired
    private IOpBrowseHistoryService browseHistoryService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private IOpEntryHistoryService entryHistoryService;

    @Autowired
    IRecruitmentPositionService positionService;

    @Autowired
    private IFileDownloadService fileDownloadService;

    @Autowired
    private ISysBaseAPI sysBaseApi;

    @Autowired
    private IOpJobService opJobService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;
    @Autowired
    private ISysAreaService sysAreaService;
    @Autowired
    private ISysIndustryService sysIndustryService;
    @Autowired
    private IDictItemService dictItemService;


    /**
     * 数据报表-简历量统计-列表导出excel
     *
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public void exportXls(HttpServletResponse response, CvResumeStatisticsParams params) {
        LambdaQueryWrapper<CvResumeStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CvResumeStatistics::getDelFlag, false);
        if (params.getStartTime() != null) {
            queryWrapper.ge(CvResumeStatistics::getCreateTime, params.getStartTime());
        }
        if (params.getEndTime() != null) {
            queryWrapper.le(CvResumeStatistics::getCreateTime, cn.hutool.core.date.DateUtil.endOfDay(cn.hutool.core.date.DateUtil.parse(params.getEndTime())));
        }
        if (StringUtils.isNotBlank(params.getId())) {
            String id = params.getId();
            String a =",";
            if (id.contains(a)) {
                queryWrapper.in(CvResumeStatistics::getId, id
                    .split(","));
            } else {
                queryWrapper.in(CvResumeStatistics::getId, id
                );
            }
        }
        queryWrapper.orderByDesc(CvResumeStatistics::getCreateTime);
        List<CvResumeStatistics> list = cvResumeStatisticsService.list(queryWrapper);
        ExcelUtil<CvResumeStatisticsVO> excelUtil = new ExcelUtil<>();
        excelUtil.buildExcel(response, cvResumeStatisticsConvert.toVO(list));
    }

    /**
     * 招聘报表-招聘进度及发布岗位-导出下面的列表
     *
     * @param params
     * @return
     */
    @GetMapping("/jobInfos")
    public void getStatisticsInfo(HttpServletResponse response, StatisticsInfoParams params) {
        LambdaQueryWrapper<OpJob> jobQuery = new LambdaQueryWrapper<>();
        jobQuery.eq(OpJob::getRecruitmentState, 0);
        if (StringUtils.isNotBlank(params.getJobName())) {
            jobQuery.like(OpJob::getJobName, params.getJobName());
        }
        if (params.getStartTime() != null) {
            jobQuery.ge(OpJob::getCreateTime, params.getStartTime());
        }
        if (params.getEndTime() != null) {
            jobQuery.le(OpJob::getCreateTime, cn.hutool.core.date.DateUtil.endOfDay(cn.hutool.core.date.DateUtil.parse(params.getEndTime())));
        }

        if (StringUtils.isNotBlank(params.getJobId())) {
            String id = params.getJobId();
            String b = ",";
            if (id.contains(b)) {
                jobQuery.in(OpJob::getId, id
                    .split(","));
            } else {
                jobQuery.in(OpJob::getId, id
                );
            }
        }

        List<OpJob> list = jobService.list(jobQuery);
        List<JobsStatisticsVO> resList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(e -> {
                JobsStatisticsVO res = new JobsStatisticsVO();
                res.setJobId(e.getId());
                res.setJobName(e.getJobName());
                res.setJobTime(e.getCreateTime());
                res.setPlaneCount(e.getNeedCount());
                res.setCompletionRate(new BigDecimal("0.00"));
                if (e.getDelFlag()) {
                    res.setState(2);
                    res.setStateString("已删除");
                } else {
                    if (e.getRecruitmentState() == 0) {
                        res.setState(0);
                        res.setStateString("在招");
                    } else {
                        res.setState(1);
                        res.setStateString("已下架");
                    }
                }
                EnInfo enInfo = enInfoService.getById(e.getCompanyId());
                if (enInfo == null) {
                    enInfo = new EnInfo();
                }
                res.setComName(enInfo.getEnName());
                res.setJobId(e.getId());
                res.setJobName(e.getJobName());
                res.setJobTime(e.getCreateTime());
                res.setState(e.getDelFlag() ? 2 : e.getRecruitmentState());
                res.setPlaneCount(e.getNeedCount());

                //通过初筛
                List<OpDeliveryHistory> deliveryHistories = this.deliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getDelFlag, false).eq(OpDeliveryHistory::getJobId, e.getId()).list();
                res.setDeCount(deliveryHistories.size());
                long firstScrCount = deliveryHistories.stream().filter(history -> history.getState() >= 3).count();
                res.setFirstScrCount((int) firstScrCount);
                res.setScreenCount(deliveryHistories.size());
                //面试
                List<OpInterviewHistory> interviewHistories = interviewHistoryService.lambdaQuery().eq(OpInterviewHistory::getJobId, e.getId()).list();
                res.setViewCount(CollectionUtils.isEmpty(interviewHistories) ? 0 : interviewHistories.size());
                //已入职
                long entryCount = deliveryHistories.stream().filter(history -> history.getState() == 6).count();
                res.setEntryCount((int) entryCount);
                res.setNotCount(e.getNeedCount() - (int) entryCount);
                //已发offer
                long offerCount = deliveryHistories.stream().filter(history -> ArrayUtil.contains(new int[]{5}, history.getState())).count();
                res.setOfferCount((int) offerCount);
                res.setCompletionRate(NumberUtil.round(NumberUtil.div(res.getEntryCount(), e.getNeedCount()), 2));
                resList.add(res);
            });

        }
        ExcelUtil<JobsStatisticsVO> excelUtil = new ExcelUtil<>();
        try {
            excelUtil.buildExcel(response, resList);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 招聘报表-招聘环节分析-各个职位信息统计
     *
     * @param params
     * @return
     */
    @GetMapping("/jobAnalysisInfo")
    public void jobAnalysisInfo(HttpServletResponse response, StatisticsInfoParams params) throws IOException, IllegalAccessException {
        LambdaQueryWrapper<OpJob> jobQuery = new LambdaQueryWrapper<>();
        jobQuery.eq(OpJob::getRecruitmentState, 0);
        if (StringUtils.isNotBlank(params.getJobName())) {
            jobQuery.like(OpJob::getJobName, params.getJobName());
        }
        if (params.getStartTime() != null) {
            jobQuery.ge(OpJob::getCreateTime, params.getStartTime());
        }
        if (params.getEndTime() != null) {
            jobQuery.le(OpJob::getCreateTime, cn.hutool.core.date.DateUtil.endOfDay(cn.hutool.core.date.DateUtil.parse(params.getEndTime())));
        }
        if (StringUtils.isNotBlank(params.getJobId())) {
            String id = params.getJobId();
            String b = ",";
            if (id.contains(b)) {
                jobQuery.in(OpJob::getId, id
                    .split(","));
            } else {
                jobQuery.in(OpJob::getId, id
                );
            }
        }

        List<OpJob> list = jobService.list(jobQuery);
        List<JobAnalysisVO> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(job -> {
                JobAnalysisVO vo = new JobAnalysisVO();
                vo.setAdoptRate(new BigDecimal("0.00"));
                vo.setEmployRate(new BigDecimal("0.00"));
                vo.setLossRate(new BigDecimal("0.00"));
                vo.setPositionRate(new BigDecimal("0.00"));
                vo.setViewRate(new BigDecimal("0.00"));
                vo.setFirstScrRate(new BigDecimal("0.00"));
                EnInfo enInfo = enInfoService.getById(job.getCompanyId());
                vo.setComName(enInfo.getEnName());
                vo.setComId(job.getCompanyId());
                vo.setJobId(job.getId());
                vo.setJobName(job.getJobName());
                vo.setJobTime(job.getCreateTime());

                if (job.getDelFlag()) {
                    vo.setState(2);
                    vo.setStateString("已删除");
                } else {
                    if (job.getRecruitmentState() == 0) {
                        vo.setState(0);
                        vo.setStateString("在招");
                    } else {
                        vo.setState(1);
                        vo.setStateString("已下架");
                    }
                }
                //查找此职位的投递记录
                LambdaQueryWrapper<OpDeliveryHistory> deliveryQuery = new LambdaQueryWrapper<>();
                deliveryQuery.eq(OpDeliveryHistory::getJobId, job.getId());
                List<OpDeliveryHistory> deliveryHistories = deliveryHistoryService.list(deliveryQuery);
                if (!CollectionUtils.isEmpty(deliveryHistories)) {
                    //0 未阅读  1 已阅读 2 不合适 3通过筛选4 面试 5已发offer(已录用) 6 已入职 7 被系统过滤 8未入职9反馈面试结果(通过)10反馈面试结果(不通过)
                    //初筛数量
                    //通过初筛
                    long firstScrCount = deliveryHistories.stream().filter(history -> history.getState() >= 3 && history.getScreenFlag() == true).count();
                    vo.setFirstScrCount((int) firstScrCount);
                    //初筛通过率
                    if (deliveryHistories.size() > 0) {
                        vo.setFirstScrRate(NumberUtil.round(NumberUtil.div(firstScrCount, deliveryHistories.size()), 2));
                    }
                    //面试
                    List<OpInterviewHistory> interviewHistories = interviewHistoryService.lambdaQuery().eq(OpInterviewHistory::getJobId, job.getId()).list();
                    vo.setViewCount(CollectionUtils.isEmpty(interviewHistories) ? 0 : interviewHistories.size());
                    //邀约面试率   面试邀请数量/通过初筛数量
                    if (firstScrCount > 0) {
                        vo.setViewRate(NumberUtil.round(NumberUtil.div(interviewHistories.size(), firstScrCount), 2));
                    }

                    //已面试数量
                    long alreadyViewCount = interviewHistories.stream().filter(history -> history.getOutLineState() == 1 && history.getViewResult() != null).count();
                    vo.setAlreadyViewCount((int) alreadyViewCount);
                    //接收面试数量
                    long adoptCount = interviewHistories.stream().filter(history -> history.getViewResult() != null && history.getViewResult() == 0).count();
                    vo.setAdoptCount((int) adoptCount);
                    //面试通过率  反馈结果通过人数/接受面试总数
                    long accept = interviewHistories.stream().filter(history -> history.getOutLineState() == 1).count();
                    if (accept > 0) {
                        vo.setAdoptRate(NumberUtil.round(NumberUtil.div(adoptCount, accept), 2));
                    }
                    //录用
                    List<OpEntryHistory> entryHistories = entryHistoryService.lambdaQuery().eq(OpEntryHistory::getJobId, job.getId()).list();
                    vo.setEmployCount(entryHistories.size());
                    //录用率  入职邀请数量/面试总数量
                    if (interviewHistories.size() > 0) {
                        vo.setEmployRate(NumberUtil.round(NumberUtil.div(entryHistories.size(), interviewHistories.size()), 2));
                    }
                    long entryCount = deliveryHistories.stream().filter(history -> history.getState() == 6).count();
                    vo.setEntryCount((int) entryCount);
                    long entryAccept = entryHistories.stream().filter(history -> history.getAcceptFlag() == 1).count();
                    //到岗率   已入职数量/接受入职邀请数量
                    if (entryAccept > 0) {
                        vo.setPositionRate(NumberUtil.round(NumberUtil.div(entryCount, entryAccept), 2));
                    }
                    long lossCount = entryHistories.stream().filter(history -> history.getAcceptFlag() == 2).count();
                    vo.setLossCount((int) lossCount);
                    //流失率   未接受入职邀请数量/总入职邀请数量
                    if (entryHistories.size() > 0) {
                        vo.setLossRate(NumberUtil.round(NumberUtil.div(lossCount, entryHistories.size()), 2));
                    }
                }
                result.add(vo);
            });
        }
        ExcelUtil<JobAnalysisVO> excelUtil = new ExcelUtil<>();
        excelUtil.buildExcel(response, result);
    }

    /**
     * 人才库-人才库导出
     *
     * @param params
     * @return
     */
    @GetMapping("/getUserListInfo")
    public Result getUserListInfo(EntryParam params, HttpServletRequest request) {
        log.info(">>>>>>>>>>>/admin/excel/getUserListInfo:{}", params.getRecruitType());
        FileDownload download = new FileDownload();
        download.setCreateTime(new Date());
        download.setState("EXEC");
        download.setFrom(params.getFrom());
        fileDownloadService.save(download);
        //异步导出
        ThreadUtil.execAsync(() -> {
            log.info("{}------>任务开始", params.getFrom());
            String person = "候选人";
            String chang = "专场";
            if (StrUtil.contains(params.getFrom(), person) || StrUtil.contains(params.getFrom(), chang)) {
                log.info(">>>>>>>>>>>hxr");
                this.hxrList(params, download.getId());
            } else {
                log.info(">>>>>>>>>>>exportList");
                this.exportList(params, download.getId());
            }
            log.info("{}------>任务结束", params.getFrom());
        });
        return Result.ok();
    }

    /**
     * 企业信息
     *
     * @param params
     * @return
     */
    @GetMapping("/getEnListInfo")
    public Result getEnListInfo(EnInfoAdminParams params, HttpServletRequest request) {
        log.info(">>>>>>>>>>>/admin/excel/getEnListInfo:{}");
        FileDownload download = new FileDownload();
        download.setCreateTime(new Date());
        download.setState("EXEC");
        download.setFrom(params.getFrom());
        fileDownloadService.save(download);
        //异步导出
        ThreadUtil.execAsync(() -> {
            log.info("{}------>任务开始", params.getFrom());
            this.enList(params, download.getId());
            log.info("{}------>任务结束", params.getFrom());
        });
        return Result.ok();
    }
    /**
     * 候选人列表
     *
     * @param params
     * @param downloadId
     */
    public void enList(EnInfoAdminParams params, Long downloadId) {
        LambdaUpdateChainWrapper<FileDownload> wrapper = fileDownloadService.lambdaUpdate()
                .eq(FileDownload::getId, downloadId);
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            Map<String, Object> queryMap = new HashMap<>(16);
            LambdaQueryWrapper<EnInfo> enInfoQuery = new LambdaQueryWrapper<>();
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            enInfoQuery.eq(EnInfo::getDelFlag, false);
            //state 0：审核成功
            enInfoQuery.eq(EnInfo::getState, 0);
            enInfoQuery.orderByDesc(EnInfo::getCreateTime);
            if(StrUtil.isNotEmpty(params.getId())){
                enInfoQuery.in(EnInfo::getId, params.getId().split(","));
            }
            //企业名称
            if (StrUtil.isNotBlank(params.getEnName())) {
                enInfoQuery.like(EnInfo::getEnName, params.getEnName());
            }
            //所属行业
            if (StrUtil.isNotBlank(params.getEnTrade())) {
                enInfoQuery.like(EnInfo::getEnTrade, params.getEnTrade());
            }
            //判断前端是否传入专场id
            if(StringUtils.isNotBlank(params.getSsSessionId())){
                //判断前端是否传入专场id
                enInfoQuery.inSql(EnInfo::getId,
                        "SELECT distinct company_id FROM op_job WHERE bs_id IN("+params.getSsSessionId()+") and del_flag = 0");
            }
            if(StringUtils.isNotBlank(sysUser.getAdminDivision())){
                //省级用户
                if(sysUser.getAdminDivision().endsWith("0000")){
                    enInfoQuery.eq(EnInfo::getProvince, sysUser.getAdminDivision());
                }else{
                    if("410100".equals(sysUser.getAdminDivision())){
                        //郑州市
                        enInfoQuery.eq(EnInfo::getCity, sysUser.getAdminDivision());
                        enInfoQuery.ne(EnInfo::getEnAddress, "410000,410100,410173");
                    }else if("410173".equals(sysUser.getAdminDivision())){
                        //航空港区
                        enInfoQuery.eq(EnInfo::getEnAddress, "410000,410100,410173");
                    }else{
                        //其他
                        enInfoQuery.eq(EnInfo::getCity, sysUser.getAdminDivision());
                    }
                }
                //增加企业类型查询  所属单位  gxt  工信厅
                enInfoQuery.eq(EnInfo::getAffUnit, "gxt");
            }
            List<EnInfo> data = enInfoService.list(enInfoQuery);
            List<EnInfoExcelVO> enInfoExcelVOList = new ArrayList<>();
            if (CollUtil.isNotEmpty(data)) {
                Map<String,String> industryMap =  new HashMap<>();//所属行业
                Map<String,String> subjectMap =  new HashMap<>();//专业
                //Map<String,String> sysAreaMap =  new HashMap<>();//地区表行业
                List<SysIndustry> industryList = sysIndustryService.lambdaQuery().list();
                if(CollUtil.isNotEmpty(industryList)){
                    for (SysIndustry sysIndustry: industryList) {
                        industryMap.put(sysIndustry.getId(),sysIndustry.getName());
                    }
                }
                List<SysDictItem> sysDictItemList = dictItemService.selectItemsByMainId("1324643348097257474");
                if(CollUtil.isNotEmpty(sysDictItemList)){
                    for (SysDictItem sysDictItem: sysDictItemList) {
                        subjectMap.put(sysDictItem.getItemValue(),sysDictItem.getItemText());
                    }
                }
                //List<SysArea> sysAreas = sysAreaService.lambdaQuery().list();
                //if(CollUtil.isNotEmpty(sysAreas)){
                //    for (SysArea sysArea: sysAreas) {
                //        sysAreaMap.put(sysArea.getId(),sysArea.getName());
                //    }
                //}
                for (EnInfo enInfo: data) {
                    LambdaQueryWrapper<OpJob> opjobQuery = new LambdaQueryWrapper<>();
                    opjobQuery.eq(OpJob::getCompanyId,enInfo.getId());
                    opjobQuery.eq(OpJob::getDelFlag, false);
                    if(StringUtils.isNotBlank(params.getSsSessionId())){
                        if(StringUtils.isNotBlank(params.getSsSessionId())){
                            opjobQuery.eq(OpJob::getBsId,params.getSsSessionId());
                        }
                    }
                    if(StringUtils.isNotBlank(sysUser.getAdminDivision())){
                        List<DictModel> models = sysBaseApi.queryDictItemsByCode("gxt_ss_session");
                        opjobQuery.in(OpJob::getBsId,models.stream().map(DictModel::getValue).toArray());
                    }
                    List<OpJob> opJobs = opJobService.list(opjobQuery);
                    if(CollUtil.isNotEmpty(opJobs)){
                        for (OpJob opJob: opJobs) {
                            EnInfoExcelVO enInfoExcelVO = new EnInfoExcelVO();
                            enInfoExcelVO.setEnName(enInfo.getEnName());
                            String enTrade = enInfo.getEnTrade();
                            if(StringUtils.isNotBlank(enTrade)){
                                String[] strArr = enTrade.split(",");
                                if(strArr.length == 2){
                                    String enTrade0 = industryMap.get(strArr[0]);
                                    String enTrade1 = industryMap.get(strArr[1]);
                                    if(StringUtils.isNotBlank(enTrade0)){
                                        enTrade = enTrade0;
                                        if(StringUtils.isNotBlank(enTrade1)){
                                            enTrade = enTrade0 + "," +enTrade1;
                                        }
                                    }else{
                                        if(StringUtils.isNotBlank(enTrade1)){
                                            enTrade = enTrade1;
                                        }else{
                                            enTrade = "";
                                        }
                                    }
                                }else{
                                    enTrade = industryMap.get(strArr[0]);
                                }
                            }else{
                                enTrade = "";
                            }
                            enInfoExcelVO.setEnTrade(enTrade);//所属行业
                            enInfoExcelVO.setIntroduce(enInfo.getIntroduce());
                            enInfoExcelVO.setEnNature(enInfo.getEnNature());//企业性质
                            String enGrade = "";
                            if("0".equals(enInfo.getEnGrade())){
                                enGrade = "无";
                            }else if("1".equals(enInfo.getEnGrade())){
                                enGrade = "专精特新中小企业";

                            }else if("2".equals(enInfo.getEnGrade())){
                                enGrade = "专精特新“小巨人”企业";
                            }
                            enInfoExcelVO.setEnGrade(enGrade);//企业层级
                            enInfoExcelVO.setOtherWelfare(enInfo.getOtherWelfare());//福利待遇
                            List<SysUserDepart> departs = sysUserDepartService.lambdaQuery().eq(SysUserDepart::getDepId, enInfo.getId()).list();
                            if (CollUtil.isNotEmpty(departs)) {
                                PiInfo piInfo = piInfoService.lambdaQuery().in(PiInfo::getUserId, departs.stream().map(SysUserDepart::getUserId).toArray()).eq(PiInfo::getEnRoleType, 1).eq(PiInfo::getDelFlag, false).one();
                                if (piInfo != null) {
                                    enInfoExcelVO.setName(piInfo.getName());
                                    enInfoExcelVO.setMobile(piInfo.getPhone());
                                }
                            }
                            enInfoExcelVO.setJobName(opJob.getJobName());//岗位名称
                            enInfoExcelVO.setNeedCount(opJob.getNeedCount());//招聘人数
                            enInfoExcelVO.setJobDuty(opJob.getJobDuty());//岗位职责
                            String subjectStr = "";
                            String subject = opJob.getSubject();
                            if(StringUtils.isNotBlank(subject)){
                                String[] strArr = subject.split(",");
                                for (String str: strArr) {
                                    String value = subjectMap.get(str);
                                    subjectStr = subjectStr + (StringUtils.isNotBlank(value)? value : str)+ ",";
                                }
                                subjectStr = subjectStr.substring(0,subjectStr.length()-1);
                            }
                            enInfoExcelVO.setSubject(subjectStr);//所需专业/技术要求
                            String eduLevel =opJob.getEduLevel() == null ? "无" : eduLabelUtil.getEduLevel(Convert.toInt(opJob.getEduLevel()),0);
                            enInfoExcelVO.setEduLevel(eduLevel);//学历要求
                            String minMoneyToMaxMoney = (opJob.getMaxMoney() == null || opJob.getMinMoney() == null) ? "薪资面议": opJob.getMaxMoney() + "至" + opJob.getMinMoney();
                            enInfoExcelVO.setMinMoneyToMaxMoney(minMoneyToMaxMoney);
                            //String jobArea = "";
                            //String province = opJob.getJobProvince();
                            //String city = opJob.getJobCity();
                            //String county = opJob.getJobCounty();
                            //if(StringUtils.isNotBlank(province)){
                            //    jobArea = sysAreaMap.get(province);
                            //}
                            //if(StringUtils.isNotBlank(city)){
                            //    jobArea = jobArea + sysAreaMap.get(city);
                            //}
                            //if(StringUtils.isNotBlank(county)){
                            //    jobArea = jobArea + sysAreaMap.get(county);
                            //}
                            //jobArea = jobArea + opJob.getJobArea();
                            enInfoExcelVO.setJobArea(opJob.getJobArea());
                            enInfoExcelVOList.add(enInfoExcelVO);
                        }
                    }else{
                        EnInfoExcelVO enInfoExcelVO = new EnInfoExcelVO();
                        List<SysUserDepart> departs = sysUserDepartService.lambdaQuery().eq(SysUserDepart::getDepId, enInfo.getId()).list();
                        enInfoExcelVO.setEnName(enInfo.getEnName());
                        String enTrade = enInfo.getEnTrade();
                        if(StringUtils.isNotBlank(enTrade)){
                            String[] strArr = enTrade.split(",");
                            if(strArr.length == 2){
                                enTrade = industryMap.get(strArr[0])+ ","+ industryMap.get(strArr[0]) ;

                            }else{
                                enTrade = industryMap.get(strArr[0]);
                            }
                        }
                        enInfoExcelVO.setEnTrade(enTrade);
                        enInfoExcelVO.setIntroduce(enInfo.getIntroduce());
                        enInfoExcelVO.setEnNature(enInfo.getEnNature());//企业性质
                        String enGrade = "";
                        if("0".equals(enInfo.getEnGrade())){
                            enGrade = "无";
                        }else if("1".equals(enInfo.getEnGrade())){
                            enGrade = "专精特新中小企业";

                        }else if("2".equals(enInfo.getEnGrade())){
                            enGrade = "专精特新“小巨人”企业";
                        }
                        enInfoExcelVO.setEnGrade(enGrade);//企业层级
                        enInfoExcelVO.setOtherWelfare(enInfo.getOtherWelfare());//福利待遇
                        if (CollUtil.isNotEmpty(departs)) {
                            PiInfo piInfo = piInfoService.lambdaQuery().in(PiInfo::getUserId, departs.stream().map(SysUserDepart::getUserId).toArray()).eq(PiInfo::getEnRoleType, 1).eq(PiInfo::getDelFlag, false).one();
                            if (piInfo != null) {
                                enInfoExcelVO.setName(piInfo.getName());
                                enInfoExcelVO.setMobile(piInfo.getPhone());
                            }
                        }
                        enInfoExcelVOList.add(enInfoExcelVO);
                    }
                }
            }
            EasyExcel.write(stream, EnInfoExcelVO.class).sheet().autoTrim(true).doWrite(enInfoExcelVOList);
            Map upload = (Map) sysBaseApi.uploadToLocal(stream.toByteArray(), "public/admin/excel", "导出企业信息.xlsx", -11, true);
            wrapper.set(FileDownload::getUrl, upload.get("url"))
                    .set(FileDownload::getState, "FINISHED")
                    .set(FileDownload::getFinishTime, new Date())
                    .update();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            wrapper.set(FileDownload::getState, "FAIL")
                    .update();
        }
    }


    /**
     * 候选人列表
     *
     * @param params
     * @param downloadId
     */
    public void hxrList(EntryParam params, Long downloadId) {
        LambdaUpdateChainWrapper<FileDownload> wrapper = fileDownloadService.lambdaUpdate()
            .eq(FileDownload::getId, downloadId);
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            Map<String, Object> queryMap = new HashMap<>(16);
            if(StrUtil.isNotBlank(params.getDataId())){
                queryMap.put("deliveryId", params.getDataId().split(","));
            }
            queryMap.put("sysFrom", params.getSysFrom());
            queryMap.put("bsType", params.getBsType());
            queryMap.put("bsId", params.getSsId());
            queryMap.put("state", null);
            int five = 5;
            if (params.getState() != null) {
                if (params.getState() == 0) {
                    queryMap.put("state", new Integer[]{0, 1});
                } else if (params.getState() == five) {
                    queryMap.put("state", new Integer[]{5, 9});
                } else {
                    queryMap.put("state", new Integer[]{params.getState()});
                }
            }
            queryMap.put("jobName", params.getJobName());
            log.info(">>>>>>>>>>>>>>>>>>>ExcelController hxr RecruitType:{}",params.getRecruitType());
            if(StringUtils.isNotBlank(params.getRecruitType())){

                queryMap.put("recruitType", params.getRecruitType());
            }

            queryMap.put("enName", params.getComName());
            queryMap.put("name", params.getUserName());
            //            应聘时间范围 0 近三个月 1近半年
//            queryMap.put("createTimeBegin", null);
//            queryMap.put("createTimeEnd", null);
//            Date now = new Date();
//            if (params.getTimeState() != null && params.getTimeState() == 0) {
//                queryMap.put("createTimeBegin", cn.hutool.core.date.DateUtil.offsetMonth(now, -3));
//            } else if (params.getTimeState() != null && params.getTimeState() == 1) {
//                queryMap.put("createTimeBegin", cn.hutool.core.date.DateUtil.offsetMonth(now, -6));
//            }
//            queryMap.put("createTimeEnd", now);
            if(params.getApplyBeginTime() != null && params.getApplyEndTime() != null) {
                queryMap.put("createTimeBegin",params.getApplyBeginTime());
                queryMap.put("createTimeEnd",params.getApplyEndTime());
            }

            if (params.getMinWorkYear() != null && params.getMaxWorkYear() != null) {
                if (params.getMinWorkYear() == 0 && params.getMaxWorkYear() == 0) {
                    queryMap.put("jobTimeBegin", null);
                    queryMap.put("jobTimeEnd", null);
                } else {
                    String start = DateUtil.getYearFirst(params.getMaxWorkYear());
                    String end = DateUtil.getYearLast(params.getMinWorkYear());
                    queryMap.put("jobTimeBegin", start);
                    queryMap.put("jobTimeEnd", end);
                }

            }
            IPage<OpDeliveryHistory> opDeliveryHistoryPage = this.deliveryHistoryService.resumeDeliveryList(new Page(1, -1), queryMap);
            List<OpDeliveryHistory> records = opDeliveryHistoryPage.getRecords();
            log.info(">>>>>>>>>>>>>>>>>>>opDeliveryHistoryPage.size():{}",records==null?0:records.size());
            List<TalentExcelVO> voList = new ArrayList<>();
            if (CollUtil.isNotEmpty(records)) {
                Object[] array = records.stream().map(OpDeliveryHistory::getUserId).distinct().toArray();
                List<PiInfo> list = this.piInfoService.lambdaQuery()
                    .in(PiInfo::getUserId, array)
                    .list();
                this.data(list, voList, records);
            }

            EasyExcel.write(stream, TalentExcelVO.class).sheet().autoTrim(true).doWrite(voList);
            Map upload = (Map) sysBaseApi.uploadToLocal(stream.toByteArray(), "public/admin/excel", "导出名单.xlsx", -11, true);
            wrapper.set(FileDownload::getUrl, upload.get("url"))
                .set(FileDownload::getState, "FINISHED")
                .set(FileDownload::getFinishTime, new Date())
                .update();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            wrapper.set(FileDownload::getState, "FAIL")
                .update();
        }
    }

    public void data(List<PiInfo> piInfos, List<TalentExcelVO> receive, List<OpDeliveryHistory> deliveryHistories) {
        piInfos.forEach(e -> {
            TalentExcelVO vo = new TalentExcelVO();

            vo.setIdNumber(e.getR6());//2022年3月12日16:46:09 zhf  增加导出身份证号功能
            String userId = e.getUserId();
            CvResume resume = resumeService.lambdaQuery()
                .eq(CvResume::getUserId, userId)
                .eq(CvResume::getDelFlag, false)
                .eq(CvResume::getType, 0)
                .eq(CvResume::getLanType, 0)
                .one();
            if (resume != null) {
                String resumeType = resume.getResumeType() == 1 ? "社招" : "校招";
                vo.setResumeType(resumeType);
                vo.setOffice(resume.getOtherSituations());
            }
            List<OpDeliveryHistory> deliveryHistoryList = deliveryHistories;
            if (deliveryHistoryList == null) {
                deliveryHistoryList = deliveryHistoryService.lambdaQuery()
                    .eq(OpDeliveryHistory::getUserId, userId)
                    .eq(OpDeliveryHistory::getDelFlag, 0)
                    .orderByDesc(OpDeliveryHistory::getCreateTime).list();
            } else {
                deliveryHistoryList = deliveryHistories.stream().filter(el -> StrUtil.equals(el.getUserId(), userId)).collect(Collectors.toList());
            }
            // 根据最新的投递记录查询出投递职位信息
            if (CollUtil.isNotEmpty(deliveryHistoryList)) {
                List<String> position = new ArrayList<>();
                List<String> companyName = new ArrayList<>();
                for (OpDeliveryHistory history : deliveryHistoryList) {
                    String jobId = history.getJobId();
                    OpJob byId = jobService.getById(jobId);
                    if (null != byId) {
                        position.add(byId.getJobName());
                        EnInfo company = this.enInfoService.getById(byId.getCompanyId());
                        companyName.add(company.getEnName());
                    }
                }
                vo.setPosition(CollUtil.join(position, "\n"));
                vo.setCompanyName(CollUtil.join(companyName, "\n"));
            }
            vo.setRate(new BigDecimal("0.00"));
            if (StringUtils.isNotBlank(e.getLiveCity())) {
                String[] citys = e.getLiveCity().split(",");
                String liveCity = getTransNames("sys_area", citys, "id", "name");
                vo.setLiveCity(liveCity);
            }

            if (StringUtils.isNotBlank(e.getHomeTown())) {
                String[] citys = e.getHomeTown().split(",");
                String liveCity = getTransNames("sys_area", citys, "id", "name");
                vo.setNativePlace(liveCity);
            }
            int two = 2;
            int three = 3;
            if (e.getMaritalStatus() != null) {
                if (0 == e.getMaritalStatus()) {
                    vo.setMaritalStatus("未婚");
                } else if (1 == e.getMaritalStatus()) {
                    vo.setMaritalStatus("已婚已育");
                } else if (two == e.getMaritalStatus()) {
                    vo.setMaritalStatus("已婚未育");
                } else if (three == e.getMaritalStatus()) {
                    vo.setMaritalStatus("离异");
                }

            }

            Date birthday = e.getBirthday();
            if (birthday != null) {
                Integer age = e.getAge();
                vo.setAge(cn.hutool.core.date.DateUtil.format(birthday, "yyyy年MM月") + (age != null ? "(" + age + "岁)" : ""));
            }
            vo.setEmail(e.getEmail());
            vo.setName(e.getName());
            int d = 2;
            if (e.getSex() == null || e.getSex() == 0) {
                vo.setSex("未知");
            } else if (e.getSex() != null && e.getSex() == 1) {
                vo.setSex("男");
            } else if (e.getSex() != null && e.getSex() == d) {
                vo.setSex("女");
            }
            vo.setPhone(e.getPhone());
            vo.setPolitics(e.getPolitical());

            LambdaQueryWrapper<CvUserEduInfo> eduQuery = new LambdaQueryWrapper<>();
            eduQuery.eq(CvUserEduInfo::getDelFlag, false).eq(CvUserEduInfo::getUserId, e.getUserId()).orderByDesc(CvUserEduInfo::getStartEduTime);
            //                        .orderByDesc(CvUserEduInfo::getEduLevel);
            //教育经历
            List<CvUserEduInfo> eduInfos = eduInfoService.list(eduQuery);
            if (!CollectionUtils.isEmpty(eduInfos)) {

                StringBuffer education = new StringBuffer();
                for (CvUserEduInfo eduInfo : eduInfos) {
                    //就读时间  学校名称    专业  学历
                    String info = StrUtil.format("{}-{}  {}  {}  {}  {}",
                        cn.hutool.core.date.DateUtil.format(eduInfo.getStartEduTime(), "yyyy.MM"),
                        cn.hutool.core.date.DateUtil.format(eduInfo.getEndEduTime(), "yyyy.MM"),
                        eduInfo.getSchoolName(), eduInfo.getMajor(), eduLabelUtil.getEduLevel(eduInfo.getEduLevel())
                        , "1".equalsIgnoreCase(eduInfo.getR2()) ? "全日制" : "非全日制"//

                    );
                    education.append(info).append("\n");
                }
                vo.setEducation(education.toString().trim());

                vo.setFullTimeLable("1".equalsIgnoreCase(eduInfos.get(0).getR2()) ? "是" : "否");
            }

            LambdaQueryWrapper<CvUserWorkInfo> workInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            workInfoLambdaQueryWrapper.eq(CvUserWorkInfo::getDelFlag, false).eq(CvUserWorkInfo::getUserId, e.getUserId()).orderByDesc(CvUserWorkInfo::getWorkStartTime);
            //工作经历
            List<CvUserWorkInfo> workInfos = workInfoService.list(workInfoLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(workInfos)) {
                StringBuffer work = new StringBuffer();
                for (CvUserWorkInfo workInfo : workInfos) {
                    if (StrUtil.isNotBlank(workInfo.getPositionName())) {
                        String[] array = workInfo.getPositionName().split(",");
                        String positionId = array[array.length - 1];
                        String jobName=null;
                        if(StringUtils.equals(positionId, CommonConstant.OTHER_POSITION)&&StringUtils.isNotBlank(workInfo.getOtherPosition())){
                            jobName = workInfo.getOtherPosition();
                        }
                        else{
                            jobName = getTransName("recruitment_position", positionId, "id", "name");
                        }
                        String info = StrUtil.format("{}-{}  {}  {}",
                            cn.hutool.core.date.DateUtil.format(workInfo.getWorkStartTime(), "yyyy.MM"),
//                            cn.hutool.core.date.DateUtil.format(workInfo.getWorkEndTime(), "yyyy.MM"),
                                workInfo.getWorkEndTime().equals(CommonConstant.TO_THIS_DAY)? workInfo.getWorkEndTime():cn.hutool.core.date.DateUtil.format(DateUtils.str2Date(workInfo.getWorkEndTime(), DateUtils.date_sdf.get()), "yyyy.MM"),
                            workInfo.getCompanyName(), jobName
                        );
                        work.append(info).append("\n");
                    }
                }
                vo.setWork(work.toString().trim());
            }

            LambdaQueryWrapper<CvWorkIntention> workIntentionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            workIntentionLambdaQueryWrapper.eq(CvWorkIntention::getDelFlag, false).eq(CvWorkIntention::getUserId, e.getUserId()).orderByDesc(CvWorkIntention::getCreateTime);
            List<CvWorkIntention> workIntentions = workIntentionService.list(workIntentionLambdaQueryWrapper);
            if (!CollectionUtils.isEmpty(workIntentions)) {
                CvWorkIntention workIntention = workIntentions.get(0);
                vo.setMoney(workIntention.getMinMoney() + "-" + workIntention.getMaxMoney());
                if (StrUtil.isNotBlank(workIntention.getWorkIndustry())) {
                    String[] array = workIntention.getWorkIndustry().split(",");
                    vo.setHopeIndustry(getTransName("sys_industry", array[array.length - 1], "id", "name"));
                }
            }

            //2022年4月1日11:02:30 zhf  职业特长与技能（专业技能）--->改为了职称
            //2023.03.08	yinyf	职称和证件合并为重要证书及职称
            StringBuilder infosStr = new StringBuilder();
            List<CvCertificate> cvCertificates = certificateService.lambdaQuery().eq(CvCertificate::getDelFlag, false).eq(CvCertificate::getUserId, e.getUserId()).list();
            if (!CollectionUtils.isEmpty(cvCertificates)) {
                cvCertificates.forEach(c -> {
                    infosStr.append(c.getName()).append("\r\n");
                });
            }
            LambdaQueryWrapper<CvSkills> skillsQuery = new LambdaQueryWrapper<>();
            skillsQuery.eq(CvSkills::getDelFlag, false).eq(CvSkills::getResumeId, resume.getId())
                .orderByDesc(CvSkills::getId);

            List<CvSkills> cvSkillsInfos = cvSkillsService.list(skillsQuery);
            if (CollUtil.isNotEmpty(cvSkillsInfos)) {
                cvSkillsInfos.forEach(e2 -> {
                	infosStr.append(e2.getName()).append("\r\n");
                });
            }
            vo.setImportant(infosStr.toString().trim());

            Integer browseCount = browseHistoryService.lambdaQuery().eq(OpBrowseHistory::getDelFlag, false).eq(OpBrowseHistory::getUserId, e.getUserId()).count();
            vo.setCount(browseCount == null ? "0" : String.valueOf(browseCount));
            if (browseCount != null && browseCount > 0) {
                Integer count = deliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getDelFlag, false).eq(OpDeliveryHistory::getUserId, e.getUserId()).count();
                if (count != null && count > 0) {
                    vo.setRate(new BigDecimal(count).divide(new BigDecimal(browseCount), 2));
                } else {
                    vo.setRate(BigDecimal.ZERO);
                }
            } else {
                vo.setRate(BigDecimal.ZERO);
            }
            receive.add(vo);
        });
    }

    @SneakyThrows
    public void exportList(EntryParam params, Long downloadId) {
        LambdaUpdateChainWrapper<FileDownload> wrapper = fileDownloadService.lambdaUpdate()
            .eq(FileDownload::getId, downloadId);
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            Map<String, Object> queryMap = new HashMap<>(16);
            if (StrUtil.isNotBlank(params.getJobName())) {
                List<RecruitmentPosition> positions = positionService.lambdaQuery()
                    .select(RecruitmentPosition::getId)
                    .like(RecruitmentPosition::getName, params.getJobName())
                    .list();
                queryMap.put("positions", positions.stream().map(RecruitmentPosition::getId).toArray());
            }
            if (StrUtil.isNotBlank(params.getDataId())) {
                queryMap.put("deliveryId", params.getDataId().split(","));
            }
            queryMap.put("sysFrom", params.getSysFrom());
            queryMap.put("sex", params.getSex());
            queryMap.put("bsType", params.getBsType());
            if(StringUtils.isNotBlank(params.getRecruitType())){
                queryMap.put("recruitType", params.getRecruitType());
            }
            queryMap.put("bsId", params.getSsId());
            queryMap.put("maritalStatus", params.getMaritalStatus());
            queryMap.put("state", null);
            int five = 5;
            if (params.getState() != null) {
                if (params.getState() == 0) {
                    queryMap.put("state", new Integer[]{0, 1});
                } else if (params.getState() == five) {
                    queryMap.put("state", new Integer[]{5, 9});
                } else {
                    queryMap.put("state", new Integer[]{params.getState()});
                }
            }
            queryMap.put("name", params.getUserName());
            //            应聘时间范围 0 近三个月 1近半年
            queryMap.put("createTimeBegin", null);
            queryMap.put("createTimeEnd", null);
            Date now = new Date();
            if (params.getTimeState() != null && params.getTimeState() == 0) {
                queryMap.put("createTimeBegin", cn.hutool.core.date.DateUtil.offsetMonth(now, -3));
            } else if (params.getTimeState() != null && params.getTimeState() == 1) {
                queryMap.put("createTimeBegin", cn.hutool.core.date.DateUtil.offsetMonth(now, -6));
            }
            queryMap.put("createTimeEnd", now);
            if(params.getApplyBeginTime() != null && params.getApplyEndTime() != null) {
                queryMap.put("createTimeBegin",params.getApplyBeginTime());
                queryMap.put("createTimeEnd",params.getApplyEndTime());
            }
            //工作经验
            if (params.getMinWorkYear() != null && params.getMaxWorkYear() != null) {
                if (params.getMinWorkYear() == 0 && params.getMaxWorkYear() == 0) {
                    queryMap.put("jobTimeBegin", null);
                    queryMap.put("jobTimeEnd", null);
                } else {
                    DateTime start = cn.hutool.core.date.DateUtil.offsetMonth(now, -(params.getMaxWorkYear() * 12));
                    DateTime end = cn.hutool.core.date.DateUtil.offsetMonth(now, -(params.getMinWorkYear() * 12));
                    queryMap.put("jobTimeBegin", start.toString(DatePattern.NORM_DATE_PATTERN));
                    queryMap.put("jobTimeEnd", end.toString(DatePattern.NORM_DATE_PATTERN));
                }
            }
            //期望月薪
            if (params.getMinMoney() != null && params.getMaxMoney() != null) {
                queryMap.put("minMoney", params.getMinMoney());
                queryMap.put("maxMoney", params.getMaxMoney());
            }
            if (StrUtil.isNotBlank(params.getWorkIndustry())) {
                queryMap.put("workIndustry", params.getWorkIndustry() + ",");
            }
            //年龄
            if (params.getMinAge() != null) {
                String endBirthday = cn.com.hhrcw.utils.DateUtil.getYearFirst(params.getMinAge() - 1);
                queryMap.put("endBirthday", endBirthday);

            }
            if (params.getMaxAge() != null) {
                String beginBirthday = cn.com.hhrcw.utils.DateUtil.getYearFirst(params.getMaxAge());
                queryMap.put("beginBirthday", beginBirthday);
            }
            IPage<OpDeliveryHistory> opDeliveryHistoryPage = this.deliveryHistoryService.resumeTalentList(new Page(1, -1), queryMap);
            List<String> collect = opDeliveryHistoryPage.getRecords().stream().map(OpDeliveryHistory::getUserId).distinct().collect(Collectors.toList());
            List<PiInfo> list = piInfoService.lambdaQuery().in(PiInfo::getUserId,collect).list();
            if (!CollectionUtils.isEmpty(list)) {
                List<TalentExcelVO> voList = new ArrayList<>();
                this.data(list, voList, null);
                EasyExcel.write(stream, TalentExcelVO.class).sheet().autoTrim(true).doWrite(voList);
                Map upload = (Map) sysBaseApi.uploadToLocal(stream.toByteArray(), "public/admin/excel", "导出名单.xlsx", -11, true);
                wrapper.set(FileDownload::getUrl, upload.get("url"))
                    .set(FileDownload::getState, "FINISHED")
                    .set(FileDownload::getFinishTime, new Date())
                    .update();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            wrapper.set(FileDownload::getState, "FAIL")
                .update();
        }
    }

    public String getTransNames(String table, String[] code, String column, String columnValue) {
        try {
            StringBuilder sql = new StringBuilder("select " + columnValue + " from `" + table + "` where " + column + " in (");
            for (String c : code) {
                sql.append("'" + c + "',");
            }
            sql.deleteCharAt(sql.length() - 1);
            sql.append(")");
            List<String> value = jdbcTemplate.queryForList(sql.toString(), String.class);
            //StringBuilder res = new StringBuilder();
            //if (!CollectionUtils.isEmpty(value)) {
            //    value.forEach(e -> {
            //        res.append(e + ",");
            //    });
            //    res.deleteCharAt(res.length() - 1);
            //}
            return ProvinceCityCountyUtils.getProvinceCityCountyShort(value);
        } catch (Exception e) {
            return "";
        }
    }

    public String getTransName(String table, String code, String column, String columnValue) {
        try {
            String value = jdbcTemplate.queryForObject("select " + columnValue + " from `" + table + "` where " + column + " = ?", new Object[]{code}, String.class);
            return value;
        } catch (Exception e) {
            return "";
        }
    }
}
